<template>
  <div class="procure-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>采购管理</h2>
      <p>采购信息查询与管理</p>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="采购编号">
          <el-input
            v-model="searchForm.ProcureCode"
            placeholder="请输入采购编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="供应商">
          <el-select
            v-model="searchForm.SupplierId"
            placeholder="请选择供应商"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="supplier in supplierOptions"
              :key="supplier.id"
              :label="supplier.supplierName"
              :value="supplier.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="success" @click="handleExport" :loading="exportLoading">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="procureCode" label="采购编号" width="120" />
        <el-table-column prop="procureTime" label="采购时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.procureTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="contractName" label="合同名称" width="200" />
        <el-table-column prop="contractCode" label="合同编号" width="120" />
        <el-table-column prop="supplierName" label="供应商名称" width="180" />
        <el-table-column prop="supplierCode" label="供应商编码" width="120" />
        <el-table-column prop="taxRate" label="税率" width="100">
          <template #default="{ row }">
            {{ row.taxRate }}%
          </template>
        </el-table-column>
        <el-table-column prop="taxRateType" label="税率类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTaxRateTypeTag(row.taxRateType)">
              {{ row.taxRateType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="salesTax" label="销售税额" width="120">
          <template #default="{ row }">
            ¥{{ row.salesTax }}
          </template>
        </el-table-column>
        <el-table-column prop="payment" label="付款金额" width="120">
          <template #default="{ row }">
            ¥{{ row.payment }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
         <el-table-column label="操作" width="120" fixed="right">
           <template #default="{ row }">
             <el-button type="primary" size="small" @click="handleDetail(row)">
               <el-icon><View /></el-icon>
               详情
             </el-button>
           </template>
         </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[6, 10, 20, 50, 100]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
     </el-card>

     <!-- 详情对话框 -->
     <el-dialog
       v-model="detailVisible"
       title="采购详情"
       width="800px"
       :before-close="handleDetailClose"
     >
       <div v-if="currentDetail" class="detail-content">
         <el-descriptions :column="2" border>
           <el-descriptions-item label="采购编号">
             <el-tag type="primary">{{ currentDetail.procureCode }}</el-tag>
           </el-descriptions-item>
           <el-descriptions-item label="采购时间">
             {{ formatDateTime(currentDetail.procureTime) }}
           </el-descriptions-item>
           <el-descriptions-item label="合同名称">
             {{ currentDetail.contractName }}
           </el-descriptions-item>
           <el-descriptions-item label="合同编号">
             <el-tag type="info">{{ currentDetail.contractCode }}</el-tag>
           </el-descriptions-item>
           <el-descriptions-item label="供应商名称">
             {{ currentDetail.supplierName }}
           </el-descriptions-item>
           <el-descriptions-item label="供应商编码">
             <el-tag type="success">{{ currentDetail.supplierCode }}</el-tag>
           </el-descriptions-item>
           <el-descriptions-item label="税率">
             <el-tag type="warning">{{ currentDetail.taxRate }}%</el-tag>
           </el-descriptions-item>
           <el-descriptions-item label="税率类型">
             <el-tag :type="getTaxRateTypeTag(currentDetail.taxRateType)">
               {{ currentDetail.taxRateType }}
             </el-tag>
           </el-descriptions-item>
           <el-descriptions-item label="销售税额">
             <span class="amount-text">¥{{ currentDetail.salesTax }}</span>
           </el-descriptions-item>
           <el-descriptions-item label="付款金额">
             <span class="amount-text">¥{{ currentDetail.payment }}</span>
           </el-descriptions-item>
           <el-descriptions-item label="创建时间">
             {{ formatDateTime(currentDetail.createTime) }}
           </el-descriptions-item>
           <el-descriptions-item label="状态">
             <el-tag :type="currentDetail.isDelete ? 'danger' : 'success'">
               {{ currentDetail.isDelete ? '已删除' : '正常' }}
             </el-tag>
           </el-descriptions-item>
         </el-descriptions>
       </div>
       
       <template #footer>
         <div class="dialog-footer">
           <el-button @click="handleDetailClose">关闭</el-button>
         </div>
       </template>
     </el-dialog>
   </div>
 </template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, Edit, Delete, View } from '@element-plus/icons-vue'
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'

// 使用正确的客户端
const r3 = getReadClient(0)
const w8 = getWriteClient(0)

// 接口类型定义
interface ProcureItem {
  id: number
  procureCode: string
  procureTime: string
  contractId: number
  supplierId: number
  taxRate: string
  taxRateType: string
  salesTax: number
  payment: number
  isDelete: boolean
  contractName: string
  contractCode: string
  createTime: string
  supplierCode: string
  supplierName: string
}

interface Supplier {
  id: number
  supplierName: string
  supplierCode: string
}

interface ApiResponse {
  data: {
    totalCount: number
    totalPage: number
    data: ProcureItem[]
  }
  code: number
  message: string
}

// 响应式数据
const loading = ref(false)
const tableData = ref<ProcureItem[]>([])
const exportLoading = ref(false)
const supplierOptions = ref<Supplier[]>([])

// 详情相关
const detailVisible = ref(false)
const currentDetail = ref<ProcureItem | null>(null)

// 搜索表单
const searchForm = reactive({
  ProcureCode: '',
  SupplierId: null as number | null
})

// 分页数据
const pagination = reactive({
  pageindex: 1,
  pagesize: 6,
  totalCount: 0,
  totalPage: 0
})

// 获取采购列表数据
const fetchProcureList = async () => {
  try {
    loading.value = true
    
    const params = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize,
      ProcureCode: searchForm.ProcureCode || undefined,
      SupplierId: searchForm.SupplierId || undefined
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      const paramKey = key as keyof typeof params
      if (params[paramKey] === undefined || params[paramKey] === '') {
        delete params[paramKey]
      }
    })

    console.log('API请求参数:', params)
    console.log('使用的客户端:', r3.defaults.baseURL)
    
    const response = await r3.get<ApiResponse>('/sellreadapi/api/Procure/Procurelist', { params })
    
    if (response.data.code === 200) {
      tableData.value = response.data.data.data
      pagination.totalCount = response.data.data.totalCount
      pagination.totalPage = response.data.data.totalPage
      console.log('获取到的数据:', tableData.value)
    } else {
      ElMessage.error(response.data.message || '获取采购列表失败')
    }
  } catch (error: any) {
    console.error('获取采购列表失败:', error)
    ElMessage.error(`网络请求失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 获取供应商列表
const fetchSupplierList = async () => {
  try {
    const response = await r3.get<ApiResponse>('/sellreadapi/api/Supplier/Supplierlist', {
      params: {
        pageindex: 1,
        pagesize: 1000
      }
    })
    
    if (response.data.code === 200) {
      supplierOptions.value = response.data.data.data
    }
  } catch (error: any) {
    console.error('获取供应商列表失败:', error)
    // 使用模拟数据
    supplierOptions.value = [
      { id: 1, supplierName: '螺蛳粉爱好者店铺', supplierCode: 'S001' },
      { id: 2, supplierName: '测试供应商', supplierCode: 'S002' }
    ]
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.pageindex = 1 // 重置到第一页
  fetchProcureList()
}

// 重置搜索
const handleReset = () => {
  searchForm.ProcureCode = ''
  searchForm.SupplierId = null
  pagination.pageindex = 1
  fetchProcureList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchProcureList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageindex = val
  fetchProcureList()
}

// 查看详情
const handleDetail = (row: ProcureItem) => {
  currentDetail.value = row
  detailVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentDetail.value = null
}

// 删除采购
const handleDelete = async (row: ProcureItem) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除采购 "${row.procureCode}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    ElMessage.success('删除成功')
    // 刷新列表
    fetchProcureList()
  } catch (error: any) {
    if (error.message === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败，请重试')
      console.error('删除采购失败:', error)
    }
  }
}

// 新增采购
const handleAdd = () => {
  ElMessage.info('新增功能待实现')
}

// 导出数据
const handleExport = async () => {
  try {
    exportLoading.value = true
    
    // 获取所有采购数据（不分页）
    const params = {
      pageindex: 1,
      pagesize: 10000,
      ProcureCode: searchForm.ProcureCode || undefined,
      SupplierId: searchForm.SupplierId || undefined
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      const paramKey = key as keyof typeof params
      if (params[paramKey] === undefined || params[paramKey] === '') {
        delete params[paramKey]
      }
    })

    const response = await r3.get<ApiResponse>('/sellreadapi/api/Procure/Procurelist', { params })
    
    if (response.data.code === 200) {
      const exportData = response.data.data.data
      
      if (exportData.length === 0) {
        ElMessage.warning('没有数据可导出')
        return
      }
      
      // 准备导出数据
      const excelData = exportData.map((item, index) => ({
        '序号': index + 1,
        '采购编号': item.procureCode,
        '采购时间': formatDateTime(item.procureTime),
        '合同名称': item.contractName,
        '合同编号': item.contractCode,
        '供应商名称': item.supplierName,
        '供应商编码': item.supplierCode,
        '税率': `${item.taxRate}%`,
        '税率类型': item.taxRateType,
        '销售税额': `¥${item.salesTax}`,
        '付款金额': `¥${item.payment}`,
        '创建时间': formatDateTime(item.createTime)
      }))
      
      // 生成Excel文件
      await exportToExcel(excelData, '采购列表')
      
      ElMessage.success(`导出成功，共导出 ${exportData.length} 条数据`)
    } else {
      ElMessage.error(response.data.message || '导出失败')
    }
  } catch (error: any) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 导出到Excel
const exportToExcel = async (data: any[], filename: string) => {
  try {
    // 动态导入xlsx库
    const XLSX = await import('xlsx')
    
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    
    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(data)
    
    // 设置列宽
    const colWidths = [
      { wch: 8 },   // 序号
      { wch: 15 },  // 采购编号
      { wch: 20 },  // 采购时间
      { wch: 25 },  // 合同名称
      { wch: 15 },  // 合同编号
      { wch: 20 },  // 供应商名称
      { wch: 15 },  // 供应商编码
      { wch: 10 },  // 税率
      { wch: 12 },  // 税率类型
      { wch: 12 },  // 销售税额
      { wch: 12 },  // 付款金额
      { wch: 20 }   // 创建时间
    ]
    ws['!cols'] = colWidths
    
    // 设置表头样式
    const headerStyle = {
      font: { bold: true, color: { rgb: "FFFFFF" } },
      fill: { fgColor: { rgb: "4472C4" } },
      alignment: { horizontal: "center", vertical: "center" }
    }
    
    // 应用表头样式
    const range = XLSX.utils.decode_range(ws['!ref'] || 'A1')
    for (let col = range.s.c; col <= range.e.c; col++) {
      const cellAddress = XLSX.utils.encode_cell({ r: 0, c: col })
      if (!ws[cellAddress]) ws[cellAddress] = { v: '' }
      ws[cellAddress].s = headerStyle
    }
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '采购列表')
    
    // 生成文件名（包含时间戳）
    const now = new Date()
    const timestamp = now.toISOString().slice(0, 19).replace(/[-:T]/g, '')
    const fileName = `${filename}_${timestamp}.xlsx`
    
    // 导出文件
    XLSX.writeFile(wb, fileName)
  } catch (error) {
    console.error('Excel导出失败:', error)
    throw new Error('Excel文件生成失败')
  }
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取税率类型标签样式
const getTaxRateTypeTag = (type: string) => {
  switch (type) {
    case '应锐内含':
      return 'success'
    case '应锐外含':
      return 'warning'
    default:
      return 'info'
  }
}

// 组件挂载时获取数据
onMounted(() => {
  console.log('组件挂载，开始获取数据...')
  console.log('使用的客户端基础URL:', r3.defaults.baseURL)
  fetchProcureList()
  fetchSupplierList()
})
</script>

<style scoped>
.procure-list {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  margin: 0;
}

.action-card {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

/* 卡片样式 */
:deep(.el-card) {
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 导出按钮样式 */
:deep(.el-button--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61;
  border-color: #85ce61;
}

:deep(.el-button--success:focus) {
  background-color: #67c23a;
  border-color: #67c23a;
}

/* 详情页面样式 */
.detail-content {
  padding: 20px 0;
}

.amount-text {
  font-weight: 600;
  color: #e6a23c;
  font-size: 16px;
}

:deep(.el-descriptions) {
  margin-top: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
  background-color: #f5f7fa;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-tag) {
  font-weight: 500;
}

.dialog-footer {
  text-align: right;
}
</style>
